package com.ljc;

/**
 * @author clj
 * @date 2022/8/26
 * @desc
 * Implement strStr().
 * Given two strings needle and haystack, return the index of the first occurrence of needle in haystack,
 * or -1 if needle is not part of haystack.
 * Clarification:
 * What should we return when needle is an empty string? This is a great question to ask during an interview.
 * For the purpose of this problem, we will return 0 when needle is an empty string.
 * This is consistent to C's strstr() and Java's indexOf().
 * Example 1:
 * Input: haystack = "hello", needle = "ll"
 * Output: 2
 *
 * Example 2:
 * Input: haystack = "aaaaa", needle = "bba"
 * Output: -1
 */
public class E28strStr {
    public static void main(String[] args) {
        String haystack = "abcdefg";
        String needle = "def";
        int r = strStr(haystack, needle);
        System.out.println(r);
    }

    public static int strStr(String haystack, String needle) {
        int point = -1;
        if (needle == null || needle.length() == 0) {
            return 0;
        }

        if (haystack == null || haystack.length() == 0 || haystack.length() < needle.length()) {
            return -1;
        }

        int i = 0;
        int j = 0;

        while (i < needle.length() && j < haystack.length()) {
            if (needle.charAt(i) == haystack.charAt(j)) {
                if (point == -1) {
                    point = j;
                }
                i++; j++;
            }else {
                point = -1;
                j++;
            }
        }
        return point;
    }

}
